<?php
	class LoginController extends BaseController {

		public function postIndex() {
			if(Auth::guest())
			{
				$rules = array(
					'user-login' => 'required|between:3,32|exists:users,username',
					'user-passwd'  => 'required|between:3,32'
				);

				$validator = Validator::make(Input::all(), $rules);

				if ($validator->fails())
				{
					return Redirect::back()->withInput()->withErrors($validator);
				}

				if (Auth::attempt(array('username' => Input::get('user-login'), 'password' => Input::get('user-passwd')), true) && Auth::user()->status > 0)
				{
					$ipauth = new UserIpAuth;
					$ipauth->login = Input::get('user-login');
					$ipauth->ip = Request::getClientIp();
					$ipauth->type = "allow";
					$ipauth->save();

					// Forum
					//@TODO : Fonction plz
					$cookie = Auth::user()->id."cookie.txt";
					if(File::exists($cookie)) {
						unlink($cookie);	
					}
					
					$url = "http://www.paradize.org/forum/ucp.php?mode=login";

					$ch = curl_init ($url);
					curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
					curl_setopt($ch, CURLOPT_COOKIE, $cookie);
					curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie);
					curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie);
					curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
					curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
					$response = curl_exec ($ch);

					unset($ch);

					preg_match('/name\=\"sid\" value\=\"([a-z0-9]+)\"/u', $response, $datSid);

					$data = array(
							'username' => Input::get('user-login'),
							'password' => Input::get('user-passwd'),
							'autologin' => '1',
							'redirect' => 'index.php',
							'login' => 'Connexion',
							'sid' => $datSid[1]
						);

					$ch = curl_init ($url."&sid=".$datSid[1]);
					curl_setopt($ch, CURLOPT_POST, true);
					curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
					curl_setopt($ch, CURLOPT_COOKIE, $cookie);
					curl_setopt($ch, CURLOPT_REFERER, $url);
					curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie);
					curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie);
					curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
					curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
					curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
					$response = curl_exec ($ch);
					$httpCode = curl_getinfo ($ch, CURLINFO_HTTP_CODE); 
					curl_close ($ch);

					$cookiefile = fopen($cookie,'r');
					$i = 0;
					while($row = fgets($cookiefile)) {
						if($i >= 4) {
							$row = explode('	',$row);
							setcookie($row[5],trim($row[6]),$row[4],$row[2],".paradize.org",null);
						}
						$i++;
					}
					fclose($cookiefile);
					unlink($cookie);

					// End Forum

					return Redirect::back();
				}
				else {
					$ipauth = new UserIpAuth;
					$ipauth->login = Input::get('user-login');
					$ipauth->ip = Request::getClientIp();
					$ipauth->type = "deny";
					$ipauth->save();
					return Redirect::back()->withInput()->withErrors("bla");
				}
			}
			return Redirect::back();
		}

		public function getIndex() {
			if(Auth::check()) {
				Auth::logout();
				$past = time() - 3600;
				foreach ( $_COOKIE as $key => $value )
				{
    				setcookie( $key, $value, $past, '/' );
				}
			}

			return Redirect::back();
		}

		public function getLostPassword() {
			return View::make('lostpassword.index');
		}

		public function postLostPassword() {
			if(Auth::guest())
			{
				$rules = array(
					'username' => 'required|between:3,32|exists:users,username',
				);

				$validator = Validator::make(Input::all(), $rules);

				if ($validator->fails())
				{
					return Redirect::back()->withInput()->withErrors($validator);
				}

				$user = User::where('username', '=', Input::get('username'))->first();

				$key = Hash::make("passwordrecovery".Input::get('username')."passwordrecovery");

				Mail::send("emails.recoveryrequest", array('username' => $user->username, 'key' => $key), function($message) use($user)
				{
					$message->to($user->email, $user->username)->subject('Récupération de votre mot de passe sur Paradize.org');
				});

				return View::make('lostpassword.success');
			}

			return Redirect::back();
		}

		public function getPassword() {

			$rules = array(
				'username' => 'required|alpha_num|between:3,32|exists:users,username',
				'key' => 'required'
			);

			$validator = Validator::make(Input::all(), $rules);

			if ($validator->fails())
			{
				return Redirect::route('index', 'index.html');
			}

			$hashValue = "passwordrecovery".Input::get('username')."passwordrecovery";

			if (Hash::check($hashValue, Input::get('key'))) {
				$new = str_random(20);

				$row = User::where('username', '=', Input::get('username'));

				$row->update(array('password' => Hash::make($new)));

				$user = $row->first();

				// Hack PHPBB

				define('IN_PHPBB', TRUE);

				include($_SERVER['DOCUMENT_ROOT']."../../forum/includes/functions.php");
				include($_SERVER['DOCUMENT_ROOT']."../../forum/includes/db/mysql.php");
			
				global $config, $db;
				$db	= new dbal_mysql();
				define("CONFIG_TABLE", "paradize-forum.phpbb_config");
				$randSeed = DB::table("paradize-forum.phpbb_config")->where("config_name", "=", "rand_seed")->first();
				$config['rand_seed'] = $randSeed->config_value;
				$randSeedLastUpdate = DB::table("paradize-forum.phpbb_config")->where("config_name", "=", "rand_seed")->first();
				$config['rand_seed_last_update'] = $randSeedLastUpdate->config_value;
				$pw_hash = phpbb_hash($new);

				$userforum = PhpBBUser::where("username", "=", Input::get('username'));
				$userforum->update(array("user_password" => $pw_hash, "user_passchg" => time()));

				Mail::send("emails.recovery", array('username' => $user->username, 'password' => $new), function($message) use($user)
				{
					$message->to($user->email, $user->username)->subject('Votre nouveau mot de passe sur paradize.org');
				});

				return View::make("lostpassword.pass-success");
			}

			return Redirect::route('index', 'index.html');
		}
	}